package com.csii.security.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;

public class RequestUtils {

    public static JSONObject getJSONObject(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try(InputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))) {

            char[] bodyCharBuffer = new char[1024];
            int len = 0;
            while ((len = reader.read(bodyCharBuffer)) != -1) {
                sb.append(new String(bodyCharBuffer, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StrUtil.isEmpty(sb.toString())){
            return new JSONObject();
        }
        return JSONObject.parseObject(sb.toString());
    }


    public static void getParamsToRequestAttribute(HttpServletRequest request) {
        Enumeration er = request.getParameterNames();
        while (er.hasMoreElements()) {
            String name = (String) er.nextElement();
            String value = request.getParameter(name);
            request.setAttribute(name, value);
        }
        JSONObject jsonObject = getJSONObject(request);
        if (!jsonObject.isEmpty()){
            jsonObject.entrySet().forEach(entry-> request.setAttribute(entry.getKey(),entry.getValue()));
        }
    }

}
